﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Xml.Linq;
using AutoMapper;
using DevWeb.Biztalk.DeploymentSettings.Common;

using DevWeb.Biztalk.DeploymentSettings.WebUI.Automapper;
using DevWeb.Biztalk.DeploymentSettings.WebUI.Models;
using DevWeb.Biztalk.DeploymentSettings.WebUI.Models.Export;
using BreadCrumbHelper.Core.Attributes;

namespace DevWeb.Biztalk.DeploymentSettings.WebUI.Controllers
{

   

    public class IntegrationController : BaseController
    {
        //
        // GET: /Integration/
        

        
        public IntegrationController()
        {
            //Repository = respos;
            //Repository.UnitOfWork.ProxyCreationEnabled = false;
            ////Mapper.Initialize(x => x.AddProfile<IntegrationViewProfile>());
            ////Mapper.AssertConfigurationIsValid();
        }

        public ActionResult Index()
        {
            //var integrations = Repository.All().Include("IntegrationVersion");

            var integrations = Context.Integrations.OrderBy(p => p.Name).ToList();
            var integrationviewmodels = Mapper.Map<List<IntegrationViewModel>>(integrations);
            return View(integrationviewmodels);
        }


        //public ActionResult Details(string productupgradecode)
        //{
        //    var selector = Guid.Parse(productupgradecode);
        //    var integration = Repository.All().SingleOrDefault(p => p.ProductUpgradeCode.Equals(selector));


        //    var viewitem = Mapper.Map<IntegrationViewModel>(integration);


        //    return View(viewitem);
        //}


        /// <summary>
        /// Create a new integration version
        /// </summary>
        /// <returns></returns>
        public ActionResult CreateIntegration()
        {
            var integration = new Data.CodeFirst.Integration
            {
                ProductUpgradeCode = Guid.NewGuid(),
                Name = "New Integration",
                Description = "New Integration created by: " + User.Identity.Name,
                CreateDateTime = DateTime.Now
            };

            var viewintegration = Mapper.Map<IntegrationViewModel>(integration);


            return View(viewintegration);
        }

        /// <summary>
        /// Create a new integration version
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CreateIntegration(IntegrationViewModel model)
        {
            if (ModelState.IsValid)
            {
                model.CreateDateTime = DateTime.Now;
                var integrationtosave = Mapper.Map<Data.CodeFirst.Integration>(model);

                Context.Integrations.Add(integrationtosave);
                Context.SaveChanges(System.Web.HttpContext.Current.User.Identity.Name);
                return RedirectToAction("CreateVersion", "IntegrationVersion",
                    new {id = integrationtosave.Id});
            }


            return View(model);
        }


        public ActionResult Edit(int id)
        {

            var integration = Context.Integrations.SingleOrDefault(p => p.Id.Equals(id));

            if (integration != null)
            {
                var integrationmodel = Mapper.Map<IntegrationViewModel>(integration);
                return View(integrationmodel);
            }
            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult Edit(IntegrationViewModel model)
        {
            if (ModelState.IsValid)
            {
                var dbintegration =
                     Context.Integrations.SingleOrDefault(p => p.Id.Equals(model.Id));

                if (dbintegration != null)
                {
                    var integrationmodel = Mapper.Map(model, dbintegration);
                    Context.SaveChanges(System.Web.HttpContext.Current.User.Identity.Name);
                }


                return RedirectToAction("Index");
            }
            else
            {
                return View(model);
            }
        }

        /// <summary>
        /// Create a new integration version
        /// </summary>
        /// <returns></returns>
        public ActionResult ImportFile()
        {
           

            return View();
        }

        /// <summary>
        /// Create a new integration version
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ImportFile(FormCollection form)
        {
            TempData.Remove("fileimport");
            var file = Request.Files[0] as HttpPostedFileBase;

            if (file != null && file.ContentLength > 0)
            {
                FileInfo fi = new FileInfo(file.FileName);
                string user = User.Identity.Name.Replace(@"\",@"-");
                string datetime = DateTime.Now.ToString("ddMMyyyyhhMMss");
                string filename = string.Format("Import-{1}-{0}-{2}.xml",fi.Name, user, datetime);

                var fp = Path.Combine(HttpContext.Server.MapPath("~/ImportUploads"), filename);
                file.SaveAs(fp);

                var fileIn = new FileInfo(fp);
                XElement importobj = XElement.Load(fileIn.FullName);

                ExportModel model = Helpers.XmlDeserialize<ExportModel>(importobj);

                TempData.Add("fileimport", model);
                
                return RedirectToAction("ImportFromFile", "IntegrationVersion");
            }
            return View();
        }

    }
}